var $tree = {};

var eventHandler = {
    'group1-add-button': add,
    'group2-add-button': add,
    'edit-button': edit,
    'delete-button': del
};

function add(node,id){
    swal({
            title: "新建股票池分组",
            text: "名称长度必须在3~16个字符之间",
            type: "input",
            showCancelButton: true,
            closeOnConfirm: false,
            animation: "slide-from-top",
            inputPlaceholder: "请输入分组名称",
            confirmButtonText: "确定",
            cancelButtonText: "取消"
        },
        function(inputValue){
            if (inputValue === false) return false;
            var poolName = $.trim(inputValue);
            if (poolName.length<3 || poolName.length>16) {
                swal.showInputError("名称长度不符合要求");
                return false
            }
            var group = { rowId:Math.uuid().toLowerCase(), parentId:id||'0', enable:'1', poolName:poolName };
            var newNode = {id:group.rowId,parentId:group.parentId,name:group.poolName};
            $.post('stockpool/createStockPoolGroup', group, function (res) {
                if(res.obj){
                    $tree.tree('appendNode', newNode, node);
                    swal("新建分组成功", "分组名称为: " + poolName, "success");
                }else{
                    swal("新建分组失败", "原因: " + res.msg || '网络出错', "error");
                }
            });
        });
}

function edit(node,id){
    swal({
            title: "修改股票池分组名称",
            text: "名称长度必须在3~16个字符之间",
            type: "input",
            showCancelButton: true,
            closeOnConfirm: false,
            animation: "slide-from-top",
            inputPlaceholder: "请输入分组名称",
            confirmButtonText: "确定",
            cancelButtonText: "取消"
        },
        function(inputValue){
            if (inputValue === false) return false;
            var poolName = $.trim(inputValue);
            if (poolName.length<3 || poolName.length>16) {
                swal.showInputError("名称长度不符合要求");
                return false
            }
            $.post('stockpool/updateStockPoolGroup', { rowId: id, poolName:poolName }, function (res) {
                if(res.obj){
                    $tree.tree('updateNode', node, poolName);
                    swal("修改分组名称成功", "分组名称为: " + poolName, "success");
                }else{
                    swal("修改分组名称失败", "原因: " + res.msg || '网络出错', "error");
                }
            });
        });
}

function del(node,id) {
    swal({
            title: "是否确定删除？",
            text: '该项及其子项会被立即删除，请谨慎操作！',
            showCancelButton: true,
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            customClass:'group-fieldset-hidden'
        },
        function(isConfirm){
            if (isConfirm) {
                $.post('stockpool/updateStockPoolGroup', { rowId: id, enable:'0' }, function (res) {
                    if(res.obj){
                        $tree.tree('removeNode', node);
                    }
                });
            }
        });
}

function list(parentId,cb) {
    if($.trim(parentId).length>0)
    $.post('stockpool/listStockPoolGroup', {parentId: parentId}, function (res) {
        cb(res.obj || []);
    });
}

$(function() {
    $tree = $('#tree');
    list('0',function(data){
        $tree.tree({
            data: data,
            closedIcon: $('<i class="am-icon-caret-right"></i>'),
            openedIcon: $('<i class="am-icon-caret-down"></i>'),
            onCreateLi: function(node, $li) {
                var $buttons = $('<span class="buttons"></span>').appendTo($li.find('.jqtree-element'));
                var add = '<a href="#node-'+ node.id +'" class="group2-add-button" data-node-id="'+ node.id +'"><i class="am-icon-plus-square-o"></i></a>'
                $buttons
                    .append(node.parentId=='0'?add:'')
                    .append('<a href="#node-'+ node.id +'" class="edit-button" data-node-id="'+ node.id +'"><i class="am-icon-edit"></i></a>')
                    .append('<a href="#node-'+ node.id +'" class="delete-button" data-node-id="'+ node.id +'"><i class="am-icon-minus-square-o"></i></a>');
            }
        });
    });

    $('.tree-container').on(
        'click', '.edit-button,.delete-button,.group2-add-button,.group1-add-button',
        function(e) {
            var btn = e.currentTarget;
            var btnClsName = btn.className;
            var handler = eventHandler[btnClsName];
            //var containerCssQuery = [':eq(',btnClsName == 'group1-add-button'?0:1,')'].join('');
            //var $node = $(btn).parents(containerCssQuery);
            var node = null;
            var id = $(btn).data('node-id');
            if ($.trim(id).length>0)
              node = $tree.tree('getNodeById', id);
            typeof handler == 'function' && handler(node,id);
        }
    );

});
